<!-- 章节信息 -->
<template>
  <div class="sectionInfo">
    <el-dialog
      title="章节信息"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="dialogClose">
      <el-form
        ref="ruleForm"
        :model="form"
        :rules="rules"
        label-width="80px"
        size="small">
        <el-form-item label="课程名称">
          <el-input v-model="courseName" disabled></el-input>
        </el-form-item>
        <el-form-item label="章节名称" prop="sectionName">
          <el-input v-model="form.sectionName"></el-input>
        </el-form-item>
        <el-form-item label="章节描述">
          <el-input v-model="form.description"></el-input>
        </el-form-item>
        <el-form-item label="章节排序">
          <el-input v-model="form.orderNum">
            <template slot="append">数字控制排序,数字越大越靠后</template>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose" size="small">取 消</el-button>
        <el-button type="primary" @click="onSave" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCourseById } from '@/services/courses'
import { saveOrUpdateSection } from '@/services/course-sections'
export default {
  name: 'sectionInfo',
  props: {
    courseId: {
      type: [String, Number]
    }
  },
  data () {
    return {
      courseName: '',
      form: {
        // 在向服务器传递值时,应该带上课程的id号发送请求,才能知道是在哪个课程添加章节
        courseId: this.courseId
      },
      dialogVisible: false,
      rules: {
        sectionName: [
          { required: true, message: '请填写章节名称', trigger: blur }
        ]
      }
    }
  },
  created () {
    this.getCourseById()
  },
  methods: {
    dialogClose () {
      this.dialogVisible = false
      this.form = {}
    },
    dialogOpen () {
      this.dialogVisible = true
    },
    // 通过课程 id 获取课程信息(来确定当前的课程名称)
    async getCourseById () {
      const { data } = await getCourseById({ courseId: this.courseId })
      if (data.code === '000000') {
        this.courseName = data.data.courseName
      }
    },
    // 保存或更新章节内容
    async onSave () {
      await this.$refs.ruleForm.validate()
      const { data } = await saveOrUpdateSection(this.form)
      if (data.code === '000000') {
        this.$message.success(`${this.form.id ? '更新' : '保存'}成功`)
        this.dialogClose()
        this.$emit('refresh')
      }
    },
    // 打开编辑章节内容
    sectionsEditOpen (data) {
      this.dialogVisible = true
      this.form = data
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
